﻿using Mate.Caching;
using Mate.Db.Model.Good;
using Mate.Db.SqlSugar;
using Mate.Dto.Good;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Mate.Good.Service
{
    public class GoodCategoryService : DataService<mp_good_category>, IGoodCategoryService
    {
        private readonly ICacheManager _cache;
        public GoodCategoryService(DataClient dataClient, ICacheManager cache) : base(dataClient)
        {
            this._cache = cache;
        }

        #region 获取商品分类Tree列表
        /// <summary>
        /// 获取商品分类Tree列表
        /// </summary>
        /// <param name="is_open">1启用2禁用</param>
        /// <returns></returns>
        public IList<GoodCategoryTreeModel> GetGoodCategoryTree(int? is_open = null)
        {
            var list = Queryable.Where(x => x.is_delete == 1)
              .WhereIF(is_open != null, x => x.is_open == is_open.Value)
              .ToList();
            if (list == null || list.Count == 0)
            {
                return null;
            }
            return GoodCategoryTreeItem(list, 0);
        }

        private List<GoodCategoryTreeModel> GoodCategoryTreeItem(IList<mp_good_category> list, int parentid)
        {
            return list.Where(x => x.parentid == parentid).Select((x, i) =>
            {
                return new GoodCategoryTreeModel()
                {
                    id = x.id,
                    name = x.name,
                    img=x.img,
                    parentid = x.parentid,
                    is_open = x.is_open,
                    children = list.Any(y => y.parentid == x.id) ? GoodCategoryTreeItem(list, x.id).ToList() : null
                };
            }).ToList();
        }
        #endregion
    }
}
